package com.sherllinhe.common.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：2025/5/7 12:24
 */

@Slf4j
public class JwtUtil {
    private static final String key = "hsl12388";

    //生成token
    public static String createToken(Long id,String mobile){
        DateTime now = DateTime.now();
        DateTime expireTime = now.offsetNew(DateField.HOUR, 30);
        Map<String, Object> payload = new HashMap<>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, expireTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //业务数据
        payload.put("id", id);
        payload.put("mobile", mobile);
        String token = JWTUtil.createToken(payload,key.getBytes());
        log.info("生成的JWT-token:{}",token);
        return token;
    }

    //验证token
    public static boolean validate(String token){
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        boolean validate = jwt.validate(0);
        log.info("JWT-token验证结果:{}",validate);
        return validate;
    }

    //获取token中的业务数据
    public static JSONObject getJSONObject(String token){
        JWT jwt = JWTUtil.parseToken(token).setKey(key.getBytes());
        JSONObject payloads = jwt.getPayloads();
        payloads.remove(JWTPayload.ISSUED_AT);
        payloads.remove(JWTPayload.EXPIRES_AT);
        payloads.remove(JWTPayload.NOT_BEFORE);
        log.info("JWT-token业务数据:{}",payloads);
        return payloads;
    }
}
